﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace mesoBoard.Data.Repositories
{
    public class RoleRepository : IRoleRepository
    {
        private mbEntities db;

        public RoleRepository(mbEntities mbDataContext)
        {
            this.db = mbDataContext;
        }

        public IEnumerable<Role> GetAllRoles()
        {
            return db.Roles;
        }

        public IEnumerable<InRole> GetUserInRoles(int userID)
        {
            return db.InRoles.Where(x => x.UserID == userID);
        }

        public bool RoleExists(string RoleName)
        {
            return db.Roles.FirstOrDefault(x => x.Name.ToLower() == RoleName.ToLower()) != null;
        }

        public void DeleteRole(int RoleID)
        {
            db.Roles.DeleteObject(GetRole(RoleID));
            db.SaveChanges();
        }

        public Role GetRole(int RoleID)
        {
            return db.Roles.FirstOrDefault(x => x.RoleID == RoleID);
        }

        public Role GetRole(string RoleName)
        {
            return db.Roles.FirstOrDefault(x => x.Name.ToLower() == RoleName.ToLower());
        }

        public void RemoveUserFromRole(int UserID, int RoleID)
        {
            db.InRoles.DeleteObject(db.InRoles.FirstOrDefault(x=>x.UserID == UserID && x.RoleID == RoleID));
            db.SaveChanges();
        }

        public void AddUserToRole(int UserID, int RoleID)
        {
            InRole newInRole = new InRole
            {
                RoleID = RoleID,
                UserID = UserID
            };

            db.InRoles.AddObject(newInRole);
            db.SaveChanges();
        }

        public IEnumerable<Role> GetRoles(int UserID)
        {
            return db.InRoles.Where(x => x.UserID == UserID).Select(y => y.Role);
        }

        public bool UserInRole(int UserID, int RoleID)
        {
            return db.InRoles.FirstOrDefault(x => x.UserID == UserID && x.RoleID == RoleID) == null ? false : true;
        }

        public void UpdateRole(Role TheRole)
        {
            if (TheRole.EntityKey == null)
                TheRole.EntityKey = ((Role)db.GetObjectByKey(new System.Data.EntityKey("mbEntities.Roles", "RoleID", TheRole.RoleID))).EntityKey;

            db.Roles.ApplyCurrentValues(TheRole);
            db.SaveChanges();
        }

        public void CreateRole(Role TheRole)
        {
            db.Roles.AddObject(TheRole);
            db.SaveChanges();
        }
        
      
    }
}
